package com.lw.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {

    //不需要检查的url
    private List<String> unCheckUrls;

    public void setUnCheckUrls(List<String> unCheckUrls){
        this.unCheckUrls = unCheckUrls;
    }
    public List<String> getUnCheckUrls(){
        return this.unCheckUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUrl = httpServletRequest.getRequestURI();
        /*
        contextPath:这个路径是部署在服务器上的 web 应用程序的根目录的路径，
        它通常对应于 web 应用程序在服务器上的部署位置。

        例如，假设你的 web 应用程序被部署在 Tomcat 服务器的 webapps/myapp 目录下，
        那么对于该应用程序中的任何 Servlet，
        调用 httpServletRequest.getContextPath() 都将返回 "/myapp"。

        如果 web 应用程序直接部署在 webapps 根目录下（即没有 myapp 这个子目录），
        那么返回值将是空字符串 ""
         */
        requestUrl = requestUrl.replaceAll(httpServletRequest.getContextPath(),"");
        if(unCheckUrls.contains(requestUrl)){
            //true不拦截
            return true;
        }

        if(null==httpServletRequest.getSession().getAttribute("sessionUser")){
            //没有登录，重定向到登录页面
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/users/login.action");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
